<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>二手房订单</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 50px auto;
            background: white;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .property-image {
            width: 100%;
            max-height: 400px;
            object-fit: cover;
            border-radius: 10px;
        }
        .property-details {
            margin-top: 20px;
            margin-left: 80px;
        }
        .property-details h2 {
            margin: 0;
        }
        .property-details p {
            color: #555;
        }
        .property-details .price {
            font-size: 1.5em;
            color: #e74c3c;
        }
        .cancel-button {
            margin-top: 150px;
            padding: 10px 15px;
            font-size: 1em;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            margin-left: 200px;
            color: white;
        }
        .cancel-button.enabled {
            background-color: #e74c3c;
        }
        .cancel-button.disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            margin-left: 20px;
        }
        .details-button {
            margin-top: 10px;
            padding: 10px 15px;
            font-size: 1em;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            background-color: #3498db;
            color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>二手房订单</h1>
        <hr style="width: 1288px;position: relative;right:20px">
    </div>
    <div id="property-content">
        <p>正在加载数据...</p>
    </div>
    <a href="../../test/page02.html"></a>
</div>

<script>
    const token = localStorage.getItem('token'); // 从localStorage中获取token

    document.addEventListener("DOMContentLoaded", function() {
        const userId = localStorage.getItem('userId');
        const apiUrl = `http://localhost:8080/user/getTransactionByUserId?userId=${userId}&type=0`;

        fetch(apiUrl,{
            headers: {
                'Authorization': `Bearer ${token}`, // 在请求头中添加token
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                const propertyContent = document.getElementById('property-content');
                propertyContent.innerHTML = ''; // 清空之前的内容

                if (data.code === 1 && Array.isArray(data.data)) {
                    data.data.forEach(transaction => {
                        // 创建一个新的div元素来包含每个交易项
                        const transactionElement = document.createElement('div');
                        transactionElement.classList.add('transaction-item'); // 添加一个CSS类，以便于样式管理

                        // 判断状态并设置按钮的样式和功能
                        const isPending = transaction.status === 0;
                        const buttonClass = isPending ? 'enabled' : 'disabled';
                        const buttonText = isPending ? '取消订单' : '交易完成';
                        const buttonDisabled = !isPending;

                        // 填充交易项的内容
                        transactionElement.innerHTML = `
                        <div style="display: flex">
                            <img style="width:500px;height:300px" src="${transaction.imageUrl}" alt="${transaction.title}" class="property-image">
                            <div style="display: flex">
                                    <div class="property-details">
                                <h2>${transaction.title}</h2>
                                <p>${transaction.description}</p>
                                <p><strong>房屋类型:</strong> ${transaction.houseType}</p>
                                <p class="price">价格: ¥${transaction.price.toLocaleString()}</p>
                                <p>成交价格: ¥${transaction.amount.toLocaleString()}</p>
                                <p><strong>交易日期:</strong> ${new Date(transaction.transactionDate).toLocaleDateString()}</p>
                                <p><strong>状态:</strong> ${isPending ? '待处理' : '已处理'}</p>

                            </div>
                             <div style="position: absolute;margin-left: 30%"> <button class="cancel-button ${buttonClass}" ${buttonDisabled ? 'disabled' : ''} onclick="handleCancelOrder(${transaction.transactionId}, ${transaction.status})">${buttonText}</button>
                              ${!isPending ? `<button class="details-button" onclick="redirectToDetails('${transaction.title}', ${transaction.propertyId}, ${transaction.price}, '${transaction.area}')">生成发票</button>` : ''}
                             </div>
</div>
</div>
  <hr style="width: 1288px;position: relative;right:20px">
                        `;

                        // 将这个交易项添加到内容容器中
                        propertyContent.appendChild(transactionElement);
                    });
                } else {
                    propertyContent.innerHTML = '<p>无法加载数据，请稍后再试。</p>';
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                document.getElementById('property-content').innerHTML = '<p>加载数据时出错。</p>';
            });
    });

    function handleCancelOrder(transactionId, status) {

        if (status === 0) {
            // 显示确认对话框
            const userConfirmed = confirm("确定要取消该订单吗？");
            if (userConfirmed) {
                // 用户确认后，发送带有token的删除请求
                const deleteApiUrl = `http://localhost:8080/user/deleteTransactionById?TransactionId=${transactionId}`;

                fetch(deleteApiUrl, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`, // 在请求头中添加token
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 1 && result.data === 1) {
                            alert('订单已成功取消');
                            location.reload(); // 刷新页面以更新订单状态
                        } else {
                            alert('取消订单失败，请稍后再试');
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting transaction:', error);
                        alert('取消订单时出错，请稍后再试');
                    });
            }
        } else {
            alert('该订单已完结，无法取消');
        }
    }


    function redirectToDetails(title, propertyId, price, area) {
        console.log(title, propertyId, price, area);
        const url = `../../test/page02.html?title=${encodeURIComponent(title)}&propertyId=${propertyId}&price=${price}&area=${encodeURIComponent(area)}`;
        console.log(url);
        window.location.href = url;
    }
</script>
</body>
</html>
